package org.inasnet.user;

import java.io.DataOutputStream;

import org.inasnet.Root;
import org.inasnet.util.Util;

public class PackOut extends Pack
{
	/**
	 * Class for output
	 * Don't use it directly!
	 */
	PackOut( int type, byte [] messageBytes, int messageBytesLength, DataOutputStream outputStream )
	{
		try
		{	
			outputStream.writeByte( 'I' );
			outputStream.writeByte( 'S' );
			
			if( type < 0 )
			{
				throw new Exception( "Wrong type!" ); 
			}
			
			outputStream.writeByte( type );
			
			if( messageBytes == null )
			{
				outputStream.writeShort( 0 );	
			} 
			else
			{
				if( messageBytesLength > 16000 )
				{
					throw new Exception( "Too long!" ); 
				}
				
				outputStream.writeShort( messageBytesLength );	
				outputStream.write( messageBytes, 0, messageBytesLength );
			}
			
			String log = "Pack---OUT---:  T:" + MessageType.values()[ type ]  + "; MBS:" + (( messageBytes == null )?0:messageBytesLength) + "; MB: " + Util.bytesToString( messageBytes, 10 );

			Root.log( log );
									
			outputStream.flush();
		}
		catch( Exception e )
		{
			e.printStackTrace();
		}
	}
}
